#!/usr/bin/python
# -*- coding: utf-8 -*-
import os, sys, re
from PySide.QtCore import *
from PySide.QtGui import *
from ttx_io import *

PRODUCT_NAME = "NF TTX Viewer"
VERSION = "1.0 (prototype)"
BUILD = "20121217"
AUTHOR = "Red Shen"
COMPANY = "NewFantex Ltd."
HOMEPAGE = "http://code.google.com/p/nf-ttx-viewer/"
DEFAULT_WIDTH = 800
DEFAULT_HEIGHT = 600
LOGO = "res/logo.png"
LOADING_MSG = "Loading.... large files may take times."
LICENSE_NOTICE = '''
                 This program is free software; you can redistribute it and/or modify it under the terms of the <b>GNU General Public License</b> as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
                 <br><br>
                 This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details. 
                 <br><br>
                 You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
                 '''
                
#For PyInstaller:                
def resourcePath(path):
    if hasattr(sys, "_MEIPASS"):
        return os.path.abspath(os.path.join(sys._MEIPASS,path))
    else:
        return path 
##########
                
                 
class Dialog(QDialog):
    def __init__(self):
        super(Dialog, self).__init__()
        super(Dialog, self).setWindowFlags(Qt.WindowSystemMenuHint | Qt.WindowTitleHint)
        self.initUI()
        
    def initUI(self):
        self.setFixedSize(300,320)
        self.setWindowTitle("About %s" % PRODUCT_NAME)  
        self.setWindowIcon(QIcon(resourcePath(LOGO)))
        vbox = QGridLayout()
        
        logo = QPixmap(resourcePath(LOGO))
        label = QLabel()
        label.setPixmap(logo)
        vbox.addWidget(label,0,2,1,3) 
        
        edit = QTextEdit()
        edit.setReadOnly(True)
        
        edit.setHtml('''
                     <b>%s - A free Trados TTX viwer with export function</b><br><br>
                     Version %s<br>
                     Author: %s@%s<br>
                     Homepage: <a href=\"%s\" target=\"_blank\"> %s</a><br><br>
                     %s
                     '''
                     % (PRODUCT_NAME, VERSION, AUTHOR, COMPANY, HOMEPAGE, HOMEPAGE[7:-1], LICENSE_NOTICE))
        
        vbox.addWidget(edit,1,0,1,6)
        button = QPushButton("OK")
        button.setSizePolicy(QSizePolicy.Fixed,QSizePolicy.Fixed)
        vbox.addWidget(button,2,2,1,3)
        button.clicked.connect(self.close)
        self.setLayout(vbox)        
        self.show()


class Table(QTableWidget):
    def __init__(self):
        super(Table, self).__init__()
        self.initUI()
               
    def initUI(self):
        self.setEditTriggers(QAbstractItemView.NoEditTriggers)
    
    def openFile(self, fn, stripTag):
        if fn.endswith(".ttx") or fn.endswith(".TTX"):
            data = ttxRead(fn, stripTag)
        else:
            data = ttxDirRead(fn, stripTag)
        if data:
            self.setWindowTitle(fn)
            self.setRowCount(len(data[0]))
            self.setColumnCount(3) 
            self.setHorizontalHeaderLabels(["Source", "Target", "File"])     
            self.setColumnWidth(0, 400)
            self.setColumnWidth(1, 400)
            self.setColumnWidth(2, 300)  
            warningColor = QBrush(QColor(255, 255, 0))
            for pos in range(0,len(data[0])):
                source = data[0][pos]
                target = data[1][pos]
                file = data[2][pos]
                sourceItem = QTableWidgetItem(source)
                targetItem = QTableWidgetItem(target)
                fileItem = QTableWidgetItem(file)
                if source == target:    
                    sourceItem.setBackground(warningColor)
                    targetItem.setBackground(warningColor) 
                self.setItem(pos, 0, sourceItem)  
                self.setItem(pos, 1, targetItem)                 
                self.setItem(pos, 2, fileItem)               
            self.resizeRowsToContents()
            

class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.initUI()
        
    def initUI(self):
        #Centering the main window:
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())
        ##########
        
        self.setWindowIcon(QIcon(resourcePath(LOGO)))
        self.setAcceptDrops(True)
    
        self.fileAction = QAction(QIcon(""), "Open &File", self)
        self.fileAction.setShortcut("Ctrl+F")
        self.fileAction.setStatusTip("Open TTX file")
        self.fileAction.triggered.connect(self.fileOpen)
        
        self.dirAction = QAction(QIcon(""), "Open &Directory", self)
        self.dirAction.setShortcut("Ctrl+D")
        self.dirAction.setStatusTip("Open directory which contains TTX files.")
        self.dirAction.triggered.connect(self.dirOpen)          
        
        self.txtAction = QAction(QIcon(""), "Export to &TXT", self)
        self.txtAction.setShortcut("Ctrl+T")
        self.txtAction.setStatusTip("Export TTX(s) to tab-separated values file.")
        self.txtAction.triggered.connect(self.exportTXT)

        self.tmxAction = QAction(QIcon(""), "Export to TM&X", self)
        self.tmxAction.setShortcut("Ctrl+X")
        self.tmxAction.setStatusTip("Export TTX(s) to Translation Memory eXchange(TMX) file.")
        self.tmxAction.triggered.connect(self.exportTMX)
        
        self.exitAction = QAction(QIcon(""), "Exit", self)
        self.exitAction.setShortcut("Ctrl+Q")
        self.exitAction.setStatusTip("Exit")
        self.exitAction.triggered.connect(self.close)
        
        self.stripAction = QAction(QIcon(""), "&Strip Tags", self, checkable=True)
        self.stripAction.setShortcut("Ctrl+S")    
        self.stripAction.setStatusTip("Strip all tags in TTX segments.")  
        self.stripAction.triggered.connect(self.stripStatus)
        self.stripAction.setChecked(True)
        
        self.aboutAction = QAction(QIcon(""), "&About %s" % PRODUCT_NAME, self)
        self.aboutAction.setShortcut("Ctrl+A")
        self.aboutAction.setStatusTip("About %s" % PRODUCT_NAME)
        self.aboutAction.triggered.connect(self.aboutDialog)        
        
        self.menubar = self.menuBar()
        self.fileMenu = self.menubar.addMenu("&File")
        self.fileMenu.addAction(self.fileAction)
        self.fileMenu.addAction(self.dirAction)
        self.fileMenu.addAction(self.txtAction)
        self.fileMenu.addAction(self.tmxAction)
        self.fileMenu.addAction(self.exitAction)
        
        self.settingsMenu = self.menubar.addMenu("&Settings")
        self.settingsMenu.addAction(self.stripAction)
        
        self.aboutMenu = self.menubar.addMenu("&About")
        self.aboutMenu.addAction(self.aboutAction)
        
        self.mdiArea = QMdiArea()
        self.mdiArea.setDocumentMode(True)
        self.mdiArea.setViewMode(QMdiArea.TabbedView)
        self.setCentralWidget(self.mdiArea)
        self.mdiArea.subWindowActivated.connect(self.ttxInfo)
        self.mdiArea.setWindowIcon(QIcon(""))
        self.statusBar().showMessage("Ready")
        
    def fileOpen(self):
        fn, _ = QFileDialog.getOpenFileName(self, "Select a TTX file", "", "Trados TTX (*.ttx *.TTX)")
        if fn:
            self.statusBar().showMessage(LOADING_MSG)       
            self.tableView(fn)
        else:
            self.statusBar().showMessage("Action canceled.")
             
    def dirOpen(self):
        options = QFileDialog.DontResolveSymlinks | QFileDialog.ShowDirsOnly
        fn = QFileDialog.getExistingDirectory(self,"Select a directory which contains multi TTX files:","", options)
        if fn:
            self.statusBar().showMessage(LOADING_MSG)      
            self.tableView(fn)
        else:
            self.statusBar().showMessage("Action canceled.")            
            
    def exportTXT(self):    
        tab = self.mdiArea.activeSubWindow()
        if tab:
            fn, _ = QFileDialog.getSaveFileName(self, "Export to TXT file", "", "Plain Text (*.txt)")
            if fn:
                self.statusBar().showMessage(LOADING_MSG)      
                txtExport(fn, tab.windowTitle(), self.stripAction.isChecked())
        else:
            msg = QMessageBox.information(self, "Attention", "Open and select a TTX file first.")
        
    def exportTMX(self):    
        tab = self.mdiArea.activeSubWindow()
        if tab:
            fn, _ = QFileDialog.getSaveFileName(self, "Export to TMX file", "", "Translation Memory eXchange (*.tmx)")
            if fn:
                self.statusBar().showMessage(LOADING_MSG)      
                tmxExport(fn, tab.windowTitle(), self.stripAction.isChecked(), PRODUCT_NAME, VERSION)
        else:
            msg = QMessageBox.information(self, "Attention", "Open and select a TTX file first.")

    def stripStatus(self):
        if self.stripAction.isChecked():
            self.statusBar().showMessage("All tags will be stripped when loading TTX files.")
        else:
            self.statusBar().showMessage("All tags will NOT be stripped when loading TTX files.")        
             
    def aboutDialog(self):  
        about = Dialog()
        about.exec_()
      
    def dragEnterEvent(self, event):
        data = event.mimeData()
        if data.hasUrls():
            event.acceptProposedAction()     
        
    def dropEvent(self, event):
        for x in range(0, len(event.mimeData().urls())):
            fn = event.mimeData().urls()[x].toLocalFile()  
            self.statusBar().showMessage(LOADING_MSG)      
            self.tableView(fn)

    def tableView(self, fn):
        subWindow = Table()
        subWindow.openFile(os.path.abspath(fn), self.stripAction.isChecked())
        self.mdiArea.addSubWindow(subWindow) 
        subWindow.show()

    def ttxInfo(self):
        if self.mdiArea.activeSubWindow():
            subWindow = self.mdiArea.activeSubWindow().widget()
            self.statusBar().showMessage("TUs: %d" % subWindow.rowCount())

        
if __name__ == "__main__":
    appdir = os.path.abspath(os.path.dirname(sys.argv[0]))
    os.chdir(appdir)
    
    app = QApplication(sys.argv)
    window1 = MainWindow()
    window1.setWindowTitle(PRODUCT_NAME)
    window1.resize(DEFAULT_WIDTH , DEFAULT_HEIGHT)
    window1.show()
    app.exec_()
    sys.exit()